<template>
  <div class="home_wrap">
    <div class="pdf_controls">
      <!-- 明显的上传按钮 -->
      <label for="pdfUpload" class="upload_btn">
        <span>选择PDF</span>
        <input
          type="file"
          id="pdfUpload"
          accept=".pdf"
          @change="handleFileUpload"
          style="display: none"
        />
      </label>

      <button
        class="annotate_btn"
        @click="toggleAnnotateMode"
        :disabled="!pdf_src"
      >
        {{ isAnnotateMode ? "退出批注" : "批注" }}
      </button>

      <button class="save_btn" @click="savePdf" :disabled="!pdf_src">
        保存PDF
      </button>
    </div>

    <div class="pdf_viewer" :style="{ width: pdf_div_width, margin: '0 auto' }">
      <div v-if="!pdf_src" class="upload_hint">
        <p>请选择或上传PDF文件开始批注</p>
      </div>

      <div
        v-for="page in pdf_pages"
        v-else
        :key="page"
        :ref="'page' + page"
        class="pdf_page_container"
      >
        <canvas
          :id="'the_canvas' + page"
          @click="isAnnotateMode && addAnnotation(page, $event)"
        ></canvas>

        <div
          class="annotation"
          v-for="(annotation, index) in annotations[page]"
          :key="index"
          :style="{
            top: annotation.y + 'px',
            left: annotation.x + 'px',
            backgroundColor: annotation.color || '#ffff88',
          }"
        >
          <div class="annotation_content">{{ annotation.content }}</div>
          <button
            class="annotation_delete"
            @click.stop="removeAnnotation(page, index)"
          >
            ×
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import jsPDF from "jspdf";
import html2canvas from "html2canvas";
let PDFJS = require("pdfjs-dist");
PDFJS.GlobalWorkerOptions.workerSrc = require("pdfjs-dist/build/pdf.worker.entry.js");

export default {
  data() {
    return {
      pdf_scale: 1.0,
      pdf_pages: [],
      pdf_div_width: "",
      pdf_src: null,
      annotations: {},
      isAnnotateMode: false,
      uploadedFile: null,
    };
  },
  methods: {
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file || file.type !== "application/pdf") {
        alert("请选择PDF文件");
        return;
      }

      this.uploadedFile = file;
      const fileURL = URL.createObjectURL(file);
      this.pdf_src = fileURL;
      this._loadFile(fileURL);
    },

    async savePdf() {
      if (!this.uploadedFile) {
        alert("请选择或上传PDF文件");
        return;
      }

      const pdf = new jsPDF();
      const loading = this.$loading({ text: "正在生成PDF..." });

      try {
        for (let pageNum = 1; pageNum <= this.pdf_pages; pageNum++) {
          const canvas = document.getElementById(`the_canvas${pageNum}`);
          if (!canvas) continue;

          // 获取整个页面容器（包含canvas和批注）
          const pageContainer = this.$refs[`page${pageNum}`][0];

          // 使用html2canvas捕获整个页面
          const imgData = await html2canvas(pageContainer, {
            scale: 2,
            logging: false,
            useCORS: true,
            allowTaint: true,
          }).then((canvas) => canvas.toDataURL("image/png"));

          // 添加到PDF
          if (pageNum > 1) pdf.addPage();
          pdf.addImage(
            imgData,
            "PNG",
            0,
            0,
            pdf.internal.pageSize.width,
            pdf.internal.pageSize.height,
            undefined,
            "FAST"
          );
        }

        pdf.save("annotated_" + this.uploadedFile.name);
      } catch (error) {
        console.error("保存PDF失败:", error);
        alert("保存PDF时出错，请重试");
      } finally {
        loading.close();
      }
    },

    toggleAnnotateMode() {
      this.isAnnotateMode = !this.isAnnotateMode;
    },

    addAnnotation(page, event) {
      const content = prompt("请输入批注内容：");
      if (!content) return;

      // 确保该页面的批注数组存在
      if (!this.annotations[page]) {
        this.annotations[page] = [];
      }

      const rect = event.target.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;

      // 添加随机颜色使批注更醒目
      const colors = ["#ffff88", "#88ff88", "#88ffff", "#ff88ff", "#ffaa77"];
      const randomColor = colors[Math.floor(Math.random() * colors.length)];

      this.annotations[page].push({
        x,
        y,
        content,
        color: randomColor,
      });
    },

    removeAnnotation(page, index) {
      if (this.annotations[page]) {
        this.annotations[page].splice(index, 1);
      }
    },

    _loadFile(url) {
      // 重置状态
      this.pdf_pages = [];
      this.annotations = {};
      this.isAnnotateMode = false;

      let loadingTask = PDFJS.getDocument(url);
      loadingTask.promise
        .then((pdf) => {
          this.pdfDoc = pdf;
          this.pdf_pages = this.pdfDoc.numPages;
          this.$nextTick(() => {
            this._renderPage(1);
          });
        })
        .catch((error) => {
          console.error("加载PDF失败:", error);
          alert("加载PDF文件失败，请检查文件格式");
        });
    },

    _renderPage(num) {
      const that = this;
      this.pdfDoc.getPage(num).then((page) => {
        const canvas = document.getElementById("the_canvas" + num);
        const ctx = canvas.getContext("2d");
        const dpr = window.devicePixelRatio || 1;
        const bsr =
          ctx.webkitBackingStorePixelRatio ||
          ctx.mozBackingStorePixelRatio ||
          ctx.msBackingStorePixelRatio ||
          ctx.oBackingStorePixelRatio ||
          ctx.backingStorePixelRatio ||
          1;
        const ratio = dpr / bsr;
        const viewport = page.getViewport({ scale: this.pdf_scale });

        canvas.width = viewport.width * ratio;
        canvas.height = viewport.height * ratio;

        canvas.style.width = viewport.width + "px";
        that.pdf_div_width = viewport.width + "px";
        canvas.style.height = viewport.height + "px";

        ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
        const renderContext = {
          canvasContext: ctx,
          viewport: viewport,
        };
        page.render(renderContext);
        if (this.pdf_pages > num) {
          this._renderPage(num + 1);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.home_wrap {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;

  .pdf_controls {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
    padding: 10px;
    background: #f5f5f5;
    border-radius: 5px;

    .upload_btn {
      padding: 8px 15px;
      background: #4caf50;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      justify-content: center;

      &:hover {
        background: #45a049;
      }
    }

    .annotate_btn {
      padding: 8px 15px;
      background: #2196f3;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;

      &:hover {
        background: #0b7dda;
      }

      &:disabled {
        background: #cccccc;
        cursor: not-allowed;
      }
    }

    .save_btn {
      padding: 8px 15px;
      background: #ff9800;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;

      &:hover {
        background: #e68a00;
      }

      &:disabled {
        background: #cccccc;
        cursor: not-allowed;
      }
    }
  }

  .pdf_viewer {
    .upload_hint {
      text-align: center;
      padding: 50px;
      font-size: 18px;
      color: #666;
      background: #f9f9f9;
      border-radius: 5px;
    }

    .pdf_page_container {
      position: relative;
      margin-bottom: 30px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

      canvas {
        display: block;
        border: 1px solid #ddd;
      }

      .annotation {
        position: absolute;
        padding: 8px;
        border-radius: 4px;
        border: 1px solid #ccc;
        max-width: 200px;
        word-wrap: break-word;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        z-index: 10;

        .annotation_content {
          margin-right: 15px;
        }

        .annotation_delete {
          position: absolute;
          top: 2px;
          right: 2px;
          background: transparent;
          border: none;
          color: #666;
          font-size: 16px;
          cursor: pointer;
          width: 20px;
          height: 20px;
          display: flex;
          align-items: center;
          justify-content: center;

          &:hover {
            color: #f44336;
          }
        }
      }
    }
  }
}
</style>
